package com.wnxy.admin.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageInfo;
import com.wnxy.admin.common.ResponseResult;
import com.wnxy.admin.common.handler.Asserts;
import com.wnxy.admin.common.handler.BusinessEnum;
import com.wnxy.admin.common.handler.GlobalVariable;
import com.wnxy.admin.common.util.AlyOssUtil;
import com.wnxy.admin.common.util.TokenUtil;
import com.wnxy.admin.dto.CarDto;
import com.wnxy.admin.entity.Car;
import com.wnxy.admin.entity.CarImage;
import com.wnxy.admin.entity.Reservation;
import com.wnxy.admin.service.ICarImageService;
import com.wnxy.admin.service.ICarService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 车辆表 前端控制器
 * </p>
 *
 * @author lqc
 * @since 2023-11-29
 */
@RestController
@RequestMapping("/car")
public class CarController {

    private final ICarService carServiceImpl;
    private final ICarImageService carImageServiceImpl;


    public CarController(ICarService carServiceImpl, ICarImageService carImageServiceImpl) {
        this.carServiceImpl = carServiceImpl;
        this.carImageServiceImpl = carImageServiceImpl;
    }

    /**
     * @author lqc
     * 车辆编辑功能
     */

    @PostMapping("/edit")
    public ResponseResult edit(@RequestBody Car car) {
        Asserts.fail(car.getCarNum().equals("")||car.getVim().equals("")
                ,BusinessEnum.CARNUM_OR_CARVIM_IS_NUll);
        // 获取数据库中与当前车辆编辑目标车牌号和车架号相匹配的车辆记录
        List<Car> matchingCars = carServiceImpl.list(Wrappers.lambdaQuery(Car.class)
                .eq(Car::getCarNum, car.getCarNum())
                .or()
                .eq(Car::getVim, car.getVim()));

        // 检查匹配的车辆记录
        for (Car matchingCar : matchingCars) {
            // 如果记录的 ID 不等于当前编辑车辆的 ID，说明车牌号或车架号重复
            if (!matchingCar.getId().equals(car.getId())) {
                return ResponseResult.fail(BusinessEnum.CARNUM_OR_CARVIM_REPEAT);
            }
        }
        // 执行更新操作
        carServiceImpl.updateById(car);
        return ResponseResult.ok();
    }
    /**
     * @author lqc
     * 车辆删除功能
     */

    @DeleteMapping("remove/{id}")
    public ResponseResult remove(@PathVariable Integer id) throws Exception {
        carServiceImpl.update(Wrappers.lambdaUpdate(Car.class)
                .eq(Car::getId, id).set(Car::getFlag, id));
        return ResponseResult.ok();
    }
    

    /**
     * @author lqc
     * 车辆分页功能
     */
    @CrossOrigin
    @GetMapping("/page/{pageNum}/{pageSize}")
    public ResponseResult page(@PathVariable Integer pageNum,
                               @PathVariable Integer pageSize,
                               @RequestParam(required = false) String keyword) {
        PageInfo<CarDto> page = carServiceImpl.getAll(pageNum, pageSize, keyword);

        return ResponseResult.ok(page);
    }

    /**
      @author lqc
     * 客户端车辆分页功能
     * 根据客户id查出车辆的分页功能
     */
    @CrossOrigin
    @GetMapping("/cpage/{pageNum}/{pageSize}")
    public ResponseResult cpage(@PathVariable Integer pageNum,
                               @PathVariable Integer pageSize,
                                @RequestParam Integer id,
                               @RequestParam(required = false) String keyword) {
        PageInfo<CarDto> page = carServiceImpl.cGetAll(pageNum, pageSize, keyword,id);
        return ResponseResult.ok(page);
    }



    /**
     * @author lqc
     * 车辆添加功能
     */

    @CrossOrigin
    @PostMapping("/add")
    public ResponseResult add(@RequestBody Car car, @RequestHeader("Authorization") String token) {
        Asserts.fail(!StringUtils.hasLength(token), BusinessEnum.CARNUM_OR_CARVIM_IS_NUll);
        Integer staffId = Integer.valueOf(TokenUtil.getPayLoad(token.replace("Bearer", ""), "staffId"));
        Asserts.fail(car.getCarNum().equals("")||car.getVim().equals("")
                ,BusinessEnum.CARNUM_OR_CARVIM_IS_NUll);
        // 获取数据库中与当前车辆编辑目标车牌号和车架号相匹配的车辆记录
        List<Car> matchingCars = carServiceImpl.list(Wrappers.lambdaQuery(Car.class)
                .eq(Car::getCarNum, car.getCarNum())
                .or()
                .eq(Car::getVim, car.getVim()));
        // 检查匹配的车辆记录
        for (Car matchingCar : matchingCars) {
            // 如果记录的 ID 不等于当前编辑车辆的 ID，说明车牌号或车架号重复
            if (!matchingCar.getId().equals(car.getId())) {
                return ResponseResult.fail(BusinessEnum.CARNUM_OR_CARVIM_REPEAT);
            }
        }
        car = isCustomer(car, staffId);

        carServiceImpl.save(car);
        GlobalVariable.CAR_NUM = car.getCarNum();
        return ResponseResult.ok();
    }

    private Car isCustomer(Car car, Integer staffId) {
        if (null == car.getCustomerId()) {
            car.setCustomerId(staffId);
            return car;
        }
        return car;
    }


}
